import { objKeySort } from '@/utils/objkeysort'
// import { clientSign } from '@/utils/clientsign.js'
import { getToken } from '@/utils/auth'
import axios from 'axios'
import qs from 'qs'
import CryptoJS from 'crypto-js'
const admin_url = '/customerAdmin'

// 获取sign签名
function getSign(signBefore) {
  const arr = ['appSecret', 'timestamp', 'nonceStr', 'token', 'body']
  let str = ''
  arr.forEach((item) => {
    const value = signBefore[item]
    if (!value) {
      return
    } else {
      str += `&${item}=${signBefore[item]}`
    }
  })
  return CryptoJS.MD5(str.substr(1)).toString()
}

// 是否为开发环境
const isDev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'

let appId, appSecret, nonceStr
if (isDev) {
  appId = 'eHpLCvak'
  appSecret = '906a55977d81220837e3dc90141f1458c46806f1'
  nonceStr = 'YlCustomerAdmin'
} else {
  appId = 'QCpkZiRz'
  appSecret = '1a652cf5ff1fbefa63c652f74d703c7819c4c0d8'
  nonceStr = 'YlCustomerAdmin'
}

const timestamp = Date.now()
const signBefore = {
  appSecret,
  timestamp,
  nonceStr
}

/**
 * 导出
 */
export function exportGameData(data = {}) {
  return new Promise((resolve, reject) => {
    data = objKeySort(data)
    data = qs.parse(data)
    const body = JSON.stringify(data)
    if (data) {
      var words = CryptoJS.enc.Utf8.parse(body)
      var base64 = CryptoJS.enc.Base64.stringify(words)
      signBefore.body = base64
      signBefore.token = getToken()[0]
    }
    const sign = getSign(signBefore)
    axios({
      method: 'post',
      url: process.env.VUE_APP_BASE_API + admin_url + '/front/v1/template/getExcelTemplate', // 请求地址
      timeout: 60000, // 请求超时时间
      data,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        token: getToken()[0],
        app_id: appId,
        timestamp,
        nonce_str: nonceStr,
        sign
      },
      responseType: 'blob' // 表明返回服务器返回的数据类型
    }).then(
      (response) => {
        resolve(response.data)
        const blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel'
        })
        const fileNameMap = {
          customer_detail_info: '导入模板(客户)',
          customer_clue: '导入模板(线索)',
          sensitive_word: '导入模板(敏感词)'
        }
        const fileName = fileNameMap[data.templateName]
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName)
        } else {
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          // 释放内存
          window.URL.revokeObjectURL(link.href)
        }
      },
      (err) => {
        reject(err)
      }
    )
  })
}
